import Https from "@/utils/Https";
import { ActionType, ProTable } from "@ant-design/pro-components";
import React, { useState, FC, useRef, useEffect } from "react";
import {
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Space,
  Alert,
  Spin,
  GetProp,
} from "antd";
import { calcColumns } from "../configFile";
import BatchSign from "./BatchSign"; //批量签到数据
import ReservationRecord from "./reservationRecord";
const AppointedStudents: FC<any> = (props) => {
  const { cardInfo, reload, onSuccess } = props;
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const InputRef = useRef();
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [open, setOpen] = useState("");
  const [reservationInfo, setReservationInfo] = useState({}); //预约记录详情
  const [title, setTitle] = useState("");
  const [messageStatus, setMessageStatus] = useState("");
  const [messageText, setMessageText] = useState("");
  //获取已约学员信息
  const getList = async (obj) => {
    let params = {
      ...obj,
      courseScheduleId: cardInfo.id,
    };
    setLoading(true);
    let records = [];
    let total = 0;
    let res: any = await Https.get(
      "/course/sched/scheduleBookRecordList",
      params,
      true
    );
    setLoading(false);
    if (res.code == 200 && res.data) {
      records = res.data.records;
      total = res.data.total;
    } else {
      message.error(res.msg);
    }
    return {
      success: true,
      data: records,
      total,
    };
  };

  //获取选中的列
  const rowSelectChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys);
  };
  //签到码改变事件
  const onChangeText: GetProp<typeof Input.OTP, "onChange"> = async (text) => {
    setLoading(true);
    InputRef.current && InputRef.current.blur();
    let params = {
      classCode: text,
      bookRecordId: reservationInfo.id,
    };
    let res = await Https.get("/course/sched/signIn", params, true);
    setLoading(false);
    if (res.code == 200) {
      setMessageStatus("success");
      setTimeout(() => {
        actionRef.current && actionRef.current.reload();
        onSuccess();
        setOpen("");
      }, 2000);
    } else {
      setMessageStatus("error");
      form.resetFields();
      setMessageText(res.msg);
    }
  };
  //取消预约
  const cancelAppinted = async (id) => {
    let res = await Https.get(
      "/course/sched/cancelRecord",
      { recordId: id },
      true
    );
    if (res.code == 200) {
      message.success("取消成功");
      onSuccess();
      actionRef.current && actionRef.current.reload();
    } else {
      message.error(res.msg);
    }
  };
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    width: 200,
    render: (_, record) => {
      return (
        <Space>
          <a
            onClick={() => {
              setOpen("details");
              setReservationInfo(record);
            }}
          >
            详情
          </a>
          {record.signinFlag == "0" && record.status == "2" && (
            <a
              onClick={() => {
                setOpen("sign");
                setReservationInfo(record);
                form.resetFields();
                setMessageStatus("");
                setMessageText("");
                setTitle(
                  `签到(${record.wechatUserName}:${record.wechatUserPhone})`
                );
              }}
            >
              签到
            </a>
          )}
          {record.status == "2" && record.signinFlag == "0" && (
            <Popconfirm
              title="是否确认取消当前课程的预约?"
              onConfirm={() => {
                cancelAppinted(record.id);
              }}
            >
              <a style={{ color: "red" }}>取消预约</a>
            </Popconfirm>
          )}
        </Space>
      );
    },
  };
  useEffect(() => {
    if (cardInfo.id) {
      actionRef.current && actionRef.current.reload();
    }
  }, [cardInfo, reload]);
  return (
    <div key="reservation">
      <ProTable
        key="tableOne"
        columns={calcColumns({ operate })}
        rowKey="id"
        actionRef={actionRef}
        loading={loading}
        search={false}
        rowSelection={{
          onChange: rowSelectChange,
          selectedRowKeys,
          getCheckboxProps: (record) => ({
            // 根据数据项的属性动态设置选择框属性
            disabled: record.signinFlag == "1" || record.status != "2", // 禁用属性会使选择框不可点击
          }),
        }}
        scroll={{ x: 900 }}
        tableAlertRender={({ selectedRowKeys }) => {
          return (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a
                  style={{ marginInlineStart: 8 }}
                  onClick={() => {
                    setSelectedRowKeys([]);
                  }}
                >
                  取消选择
                </a>
              </span>
            </Space>
          );
        }}
        tableAlertOptionRender={() => {
          return (
            <a
              onClick={() => {
                setOpen("batch");
              }}
            >
              批量签到
            </a>
          );
        }}
        pagination={{
          pageSize: 10,
          showTotal: () => "",
        }}
        request={async (params) => {
          return await getList(params);
        }}
      />
      {/* 单个签到 */}
      <Modal
        title={title}
        open={open == "sign"}
        footer={null}
        onCancel={() => {
          setOpen("");
        }}
      >
        <Spin spinning={loading}>
          {messageStatus == "success" && (
            <Alert message="签到成功" type="success" showIcon />
          )}
          {messageStatus == "error" && (
            <Alert message={messageText} type="error" showIcon />
          )}
          <Form form={form} style={{ margin: "24px", height: "50px" }}>
            <Form.Item label="签到码" tooltip={"请输入6位数字"} name="code">
              <Input.OTP
                formatter={(str) => str.replace(/\s/g, "").toUpperCase()}
                onChange={onChangeText}
                disabled={messageStatus == "success"}
                ref={InputRef}
              />
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
      {/* 批量签到 */}
      <BatchSign
        open={open == "batch"}
        onClose={() => {
          setOpen("");
        }}
        onSuccess={() => {
          actionRef.current && actionRef.current.reload();
          onSuccess();
          setSelectedRowKeys([]);
        }}
        selectedRowKeys={selectedRowKeys}
      />
      {/* 预约记录详情 */}
      <ReservationRecord
        open={open == "details"}
        reservationInfo={reservationInfo}
        onClose={() => {
          setOpen("");
        }}
      />
    </div>
  );
};
export default AppointedStudents;
